<template>
  <div class="page-wrap">
    <el-card shadow="never">
      <div class="toolbar">
        <el-input v-model="filters.search" placeholder="搜索名称/编码" clearable class="w-300" />
        <el-select v-model="filters.category" placeholder="类别" clearable class="w-160">
          <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
        </el-select>
      </div>

      <el-table :data="dataList" border stripe height="520px">
        <el-table-column prop="code" label="编码" width="120" />
        <el-table-column prop="name" label="名称" min-width="180" />
        <el-table-column prop="category" label="类别" width="120" />
        <el-table-column prop="warehouse" label="仓库" width="120" />
        <el-table-column prop="quantity" label="库存" width="100" />
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openLoss(row)">报损</el-button>
            <el-button size="small" @click="openGain(row)">报溢</el-button>
            <el-button size="small" @click="openAdjust(row)">调账</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card shadow="never" class="mt-16">
      <template #header>
        <div class="card-header">最近损益记录</div>
      </template>
      <el-table :data="lossHistory" border stripe height="340px">
        <el-table-column prop="date" label="日期" width="180">
          <template #default="{ row }">{{ formatDate(row.date) }}</template>
        </el-table-column>
        <el-table-column prop="productName" label="商品" min-width="160" />
        <el-table-column label="类型" width="140">
          <template #default="{ row }">{{ renderRecordType(row) }}</template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template #default="{ row }">
            <span v-if="row.type==='inventory'">
              {{ row.originalQuantity }} → {{ row.actualQuantity }}
              <span :class="row.actualQuantity - row.originalQuantity >= 0 ? 'txt-success' : 'txt-danger'">
                ({{ row.actualQuantity - row.originalQuantity >= 0 ? '+' : '' }}{{ row.actualQuantity - row.originalQuantity }})
              </span>
            </span>
            <span v-else :class="row.type==='inbound' ? 'txt-success' : 'txt-danger'">
              {{ row.type==='inbound' ? '+' : '-' }}{{ row.quantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" />
      </el-table>
    </el-card>

    <!-- 报损 -->
    <el-dialog v-model="lossVisible" title="报损出库" width="520px">
      <el-form :model="lossForm" label-width="100px">
        <el-form-item label="商品"><span>{{ currentRow?.name }}（{{ currentRow?.code }}）</span></el-form-item>
        <el-form-item label="数量"><el-input-number v-model="lossForm.quantity" :min="1" /></el-form-item>
        <el-form-item label="原因">
          <el-input v-model="lossForm.reason" placeholder="如：破损/变质/丢失" />
        </el-form-item>
        <el-form-item label="备注"><el-input v-model="lossForm.remark" type="textarea" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="lossVisible=false">取消</el-button>
        <el-button type="primary" @click="onLoss">确认</el-button>
      </template>
    </el-dialog>

    <!-- 报溢 -->
    <el-dialog v-model="gainVisible" title="报溢入库" width="520px">
      <el-form :model="gainForm" label-width="100px">
        <el-form-item label="商品"><span>{{ currentRow?.name }}（{{ currentRow?.code }}）</span></el-form-item>
        <el-form-item label="数量"><el-input-number v-model="gainForm.quantity" :min="1" /></el-form-item>
        <el-form-item label="单价"><el-input-number v-model="gainForm.price" :min="0" :precision="2" /></el-form-item>
        <el-form-item label="备注"><el-input v-model="gainForm.remark" type="textarea" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="gainVisible=false">取消</el-button>
        <el-button type="primary" @click="onGain">确认</el-button>
      </template>
    </el-dialog>

    <!-- 调账 -->
    <el-dialog v-model="adjustVisible" title="库存调账" width="520px">
      <el-form :model="adjustForm" label-width="100px">
        <el-form-item label="商品"><span>{{ currentRow?.name }}（{{ currentRow?.code }}）</span></el-form-item>
        <el-form-item label="实盘数量"><el-input-number v-model="adjustForm.actualQuantity" :min="0" /></el-form-item>
        <el-form-item label="备注"><el-input v-model="adjustForm.remark" type="textarea" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adjustVisible=false">取消</el-button>
        <el-button type="primary" @click="onAdjust">确认</el-button>
      </template>
    </el-dialog>
  </div>
  </template>

  <script setup>
  import { reactive, ref, computed, onMounted } from 'vue'
  import { useStockStore } from '@/stores/stock.js'
  const store = useStockStore()

  const filters = reactive({ search: '', category: '' })
  const dataList = computed(() => store.getFilteredStock(filters))
  const categories = computed(() => Array.from(new Set(store.stockList.map(x => x.category))))

  onMounted(() => { if (!store.stockList.length) store.initializeStock() })

  const currentRow = ref(null)

  const lossVisible = ref(false)
  const gainVisible = ref(false)
  const adjustVisible = ref(false)

  const lossForm = reactive({ quantity: 1, reason: '报损', remark: '' })
  const gainForm = reactive({ quantity: 1, price: 0, remark: '' })
  const adjustForm = reactive({ actualQuantity: 0, remark: '' })

  function openLoss(row){
    currentRow.value = row
    lossForm.quantity = 1
    lossForm.reason = '报损'
    lossForm.remark = ''
    lossVisible.value = true
  }
  function openGain(row){
    currentRow.value = row
    gainForm.quantity = 1
    gainForm.price = row.costPrice || 0
    gainForm.remark = ''
    gainVisible.value = true
  }
  function openAdjust(row){
    currentRow.value = row
    adjustForm.actualQuantity = row.quantity
    adjustForm.remark = ''
    adjustVisible.value = true
  }

  function onLoss(){
    if(!currentRow.value) return
    if(lossForm.quantity <= 0) return
    if(lossForm.quantity > currentRow.value.quantity) return
    store.outboundStock({
      productId: currentRow.value.id,
      quantity: lossForm.quantity,
      reason: lossForm.reason || '报损',
      operator: '系统',
      date: new Date().toISOString(),
      remark: lossForm.remark
    })
    lossVisible.value = false
  }

  function onGain(){
    if(!currentRow.value) return
    if(gainForm.quantity <= 0) return
    store.inboundStock({
      productId: currentRow.value.id,
      quantity: gainForm.quantity,
      price: gainForm.price || currentRow.value.costPrice || 0,
      supplier: '报溢',
      date: new Date().toISOString(),
      remark: gainForm.remark
    })
    gainVisible.value = false
  }

  function onAdjust(){
    if(!currentRow.value) return
    if(adjustForm.actualQuantity < 0) return
    store.inventoryStock({
      productId: currentRow.value.id,
      actualQuantity: adjustForm.actualQuantity,
      operator: '系统',
      date: new Date().toISOString(),
      remark: adjustForm.remark
    })
    adjustVisible.value = false
  }

  const lossHistory = computed(() => {
    const list = store.getStockHistory()
    return list.filter(r => {
      if (r.type === 'inventory') return true
      if (r.type === 'outbound' && r.reason === '报损') return true
      if (r.type === 'inbound' && r.supplier === '报溢') return true
      return false
    }).slice(0, 100)
  })

  function renderRecordType(row){
    if(row.type === 'inventory') return '调账'
    if(row.type === 'outbound' && row.reason === '报损') return '报损出库'
    if(row.type === 'inbound' && row.supplier === '报溢') return '报溢入库'
    return row.type
  }
  function formatDate(d){
    try {
      return new Date(d).toLocaleString('zh-CN')
    } catch { return d }
  }
  </script>

  <style scoped>
  .page-wrap { padding: 16px; }
  .toolbar { display: flex; gap: 12px; margin-bottom: 12px; align-items: center; }
  .w-300 { width: 300px; }
  .w-160 { width: 160px; }
  .mt-16 { margin-top: 16px; }
  .card-header { font-weight: 600; }
  .txt-success { color: #16a34a; }
  .txt-danger { color: #dc2626; }
  </style>


